<?php
namespace control;
/*
*核对总账类
*/

class generalAccountClass extends adIndexClass
{
    private const page = 'generalAccount';
    private const title = '核对总账';

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "会计期间" => text(array("name" => "createTime", 'laydate' => ['type' => 'month', 'range' => '~'], 'value' => date('Y-m') . ' ~ ' . date('Y-m'))),
                    '账户名称' => selectMultiple(array('name' => 'accountId', 'table' => 'account', 'sqlField' => 'name', 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "'", 'class' => 'width200')),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= "<span class='spanButton' onclick=\"window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage')\">打印</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array();
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
            'id' => $this->post('accountId')
        );
        $and = " and subjectId !=''";
        $timeWhere = $voucherWhere = '';
        $startDate = '';
        if ($this->post('createTime')) {
            $data = explode('~', $this->post('createTime'));
            $startDate = trim($data[0]);
            $timeWhere .= self::timeComparison($this->post('createTime'), 'month', field: 'recordDate');
            $voucherWhere .= self::timeComparison($this->post('createTime'), 'month', field: 'a.recordDate');
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array('table' => "account", 'where' => $where, 'order' => "time asc"));
        static::rSet(self::$stid.self::page. 'sql', $page['fullSql']);
        static::rSet(self::$stid.self::page. 'time', $this->post('createTime'));
        //获取表头
        $tr[] = array("项目", "名称", "期初", '借方(收入)', '贷方(支出)', '余额');
        foreach ($page['array'] as $array) {
            $subject = query('subject', "id = '$array[subjectId]'");
            if (!empty($subject['id'])){
                $subjectJieInitMoney = find(array('table' => 'voucher as a join voucher_detail as b on a.id = b.orderId', 'single' => "b.subjectId = '$array[subjectId]' and b.direction = '借' and a.isTemplate = '否' and a.coid = '" . self::$coid . "' and date_format(a.recordDate,'%Y-%m') <'$startDate'", 'field' => "ifnull(sum(b.money),0) as money"))['money'];
                $subjectDaiInitMoney = find(array('table' => 'voucher as a join voucher_detail as b on a.id = b.orderId', 'single' => "b.subjectId = '$array[subjectId]' and b.direction = '贷' and a.isTemplate = '否' and a.coid = '" . self::$coid . "' and date_format(a.recordDate,'%Y-%m') <'$startDate'", 'field' => "ifnull(sum(b.money),0) as money"))['money'];
                $subjectInitMoney = $subjectJieInitMoney-$subjectDaiInitMoney;
                if ($subject['direction'] =='借'){
                    $subjectInitMoney+=$subject['initMoney'];
                }else{
                    $subjectInitMoney-=$subject['initMoney'];
                }
                $subjectInitMoney = round(self::centToYuan($subjectInitMoney),2);//科目期初金额
                $jieMoney = find(array('table' => 'voucher as a join voucher_detail as b on a.id = b.orderId', 'single' => "b.subjectId = '$array[subjectId]' and b.direction = '借' and a.isTemplate = '否' and a.coid = '" . self::$coid . "'" . $voucherWhere, 'field' => "ifnull(sum(b.money),0) as money"))['money'];
                $daiMoney = find(array('table' => 'voucher as a join voucher_detail as b on a.id = b.orderId', 'single' => "b.subjectId = '$array[subjectId]' and b.direction = '贷' and a.isTemplate = '否' and a.coid = '" . self::$coid . "'" . $voucherWhere, 'field' => "ifnull(sum(b.money),0) as money"))['money'];
                $jieMoney = self::centToYuan($jieMoney);
                $daiMoney = self::centToYuan($daiMoney);

                $initMoney = find(array('table' => 'bookkeeping', 'single' => "accountId = '$array[id]' and date_format(recordDate,'%Y-%m') < '$startDate'", 'field' => "ifnull(sum(income-expenses),0) as money"))['money'];
                $initMoney += $array['initMoney'];
                $initMoney = round($initMoney,2);
                $income = find(array('table' => 'bookkeeping', 'where' => "accountId = '$array[id]'" . $timeWhere, 'sum' => "income"));
                $out = find(array('table' => 'bookkeeping', 'where' => "accountId = '$array[id]'" . $timeWhere, 'sum' => "expenses"));
                $hide = 'hide';
                if ($subjectInitMoney - $initMoney != 0) {
                    $hide = '';
                }
                if ($jieMoney - $income != 0) {
                    $hide = '';
                }
                if ($daiMoney - $out != 0) {
                    $hide = '';
                }
                $tr[] = ['会计科目', $subject['code'] . $subject['name'], $subjectInitMoney, $jieMoney, $daiMoney, $subjectInitMoney + $jieMoney - $daiMoney];
                $tr[] = ['资金账户', $array['name'], $initMoney, $income, $out, $initMoney + $income - $out];
                $tr[] = ["<span class='divider'>差异<img class='$hide' src='" . root . "img/control/no_balance.svg'/></span>", '', round($subjectInitMoney - $initMoney,2), round($jieMoney - $income,2), round($daiMoney - $out,2), round(($subjectInitMoney + $jieMoney - $daiMoney) - ($initMoney + $income - $out),2)];
            }

        }

        //控件
        $button = "";
        //返回
        $json['html'] = $button . "<form name='listForm'>" . $this->tableMany(array("tr" => $tr,"displayFields" => false)) . "</form>" . $this->homeJs() . clear;
        return json_encode($json, 320);
    }



    /**
     * 打印
     */
    public function printPage(): string
    {
        $sql = static::rGet(self::$stid.self::page . 'sql');
        $createTime = static::rGet(self::$stid.self::page . 'time');
        $timeWhere = $voucherWhere = '';
        $startDate = $endDate='';
        if ($createTime) {
            $data = explode('~', $createTime);
            $startDate = trim($data[0]);
            $endDate = trim($data[1]);
            $timeWhere .= self::timeComparison($createTime, 'month', field: 'recordDate');
            $voucherWhere .= self::timeComparison($createTime, 'month', field: 'a.recordDate');
        }
        $company =query('company',"coid = '".self::$coid."'");//公司名称
        $tempHtml = '';
        $result = self::sqlFind($sql);
        foreach ($result as $array) {
            $subject = query('subject', "id = '$array[subjectId]'");
            $subjectInitMoney = find(array('table' => 'voucher as a join voucher_detail as b on a.id = b.orderId', 'single' => "b.subjectId = '$array[subjectId]' and b.direction = '借' and a.isTemplate = '否' and a.coid = '" . self::$coid . "' and date_format(a.recordDate,'%Y-%m') <'$startDate'", 'field' => "ifnull(sum(b.money),0) as money"))['money'];
            $subjectInitMoney += $subject['initMoney'];
            $subjectInitMoney = self::centToYuan($subjectInitMoney);//科目期初金额

            $jieMoney = find(array('table' => 'voucher as a join voucher_detail as b on a.id = b.orderId', 'single' => "b.subjectId = '$array[subjectId]' and b.direction = '借' and a.isTemplate = '否' and a.coid = '" . self::$coid . "'" . $voucherWhere, 'field' => "ifnull(sum(b.money),0) as money"))['money'];
            $daiMoney = find(array('table' => 'voucher as a join voucher_detail as b on a.id = b.orderId', 'single' => "b.subjectId = '$array[subjectId]' and b.direction = '贷' and a.isTemplate = '否' and a.coid = '" . self::$coid . "'" . $voucherWhere, 'field' => "ifnull(sum(b.money),0) as money"))['money'];
            $jieMoney = self::centToYuan($jieMoney);
            $daiMoney = self::centToYuan($daiMoney);

            $initMoney = find(array('table' => 'bookkeeping', 'single' => "accountId = '$array[id]' and date_format(recordDate,'%Y-%m') < '$startDate'", 'field' => "ifnull(sum(income-expenses),0) as money"))['money'];
            $initMoney += $array['initMoney'];
            $income = find(array('table' => 'bookkeeping', 'where' => "accountId = '$array[id]'" . $timeWhere, 'sum' => "income"));
            $out = find(array('table' => 'bookkeeping', 'where' => "accountId = '$array[id]'" . $timeWhere, 'sum' => "expenses"));

            $hide = '';
            if ($subjectInitMoney - $initMoney != 0) {
                $hide = '不平';
            }
            if ($jieMoney - $income != 0) {
                $hide = '不平';
            }
            if ($daiMoney - $out != 0) {
                $hide = '不平';
            }
            $tr[] = ["差异", $hide, $subjectInitMoney - $initMoney, $jieMoney - $income, $daiMoney - $out, ($subjectInitMoney + $jieMoney - $daiMoney) - ($initMoney + $income - $out)];
            $subjectBalance =  $subjectInitMoney + $jieMoney - $daiMoney;
            $accountBalance = $initMoney + $income - $out;
            $tempHtml .= "
                            <tr class='have_border'>
                               <td>会计科目</td>
                               <td>{$subject['code']}{$subject['name']}</td>
                               <td>$subjectInitMoney</td>
                               <td>$jieMoney</td>
                               <td>$daiMoney</td>
                               <td>$subjectBalance</td>
                            </tr>
                            <tr class='have_border'>
                               <td>资金账户</td>
                               <td>{$array['name']}</td>
                               <td>$initMoney</td>
                               <td>$income</td>
                               <td>$out</td>
                               <td>$accountBalance</td>
                            </tr>
                            <tr class='have_border'>
                               <td>差异</td>
                               <td>$hide</td>
                               <td>".($subjectInitMoney - $initMoney)."</td>
                               <td>".($jieMoney - $income)."</td>
                               <td>".($daiMoney - $out)."</td>
                               <td>".($subjectBalance-$accountBalance)."</td>
                            </tr>";

        }
        $startDate = date('Y年m月',strtotime($startDate));
        $endDate = date('Y年m月',strtotime($endDate));
        $divHtml = "
                 <div>
                      <div class='printTitle' style='font-weight: bold'>核对总账</div>
                 </div>
                 <div class='table-top-title'><div>编制单位：{$company['name']}</div><div>{$startDate}至{$endDate}</div></div>
              <table class='printTable' style='width: 100%' data-op-type='block-box'>
                <tbody class='nop-fill-box'>
                <tr class='have_border'>
                   <td>项目</td>
                   <td>名称</td>
                   <td>期初余额</td>
                   <td>借方(收入)</td>
                   <td>贷方(支出)</td>
                   <td>余额</td>
                </tr>
                $tempHtml
               </tbody>
              </table>
            ";
        $html = <<<eof
                    <div id="content-box" style="display: none">
                        <div data-op-type='new-page'></div>
                    <!--    <div data-op-type="pendants">&lt;!&ndash; 定义页面部件（页眉/页脚/书签/水印背景等） &ndash;&gt;-->
                    <!--        <div class='pendant-title'>实发工资表</div>-->
                    <!--    </div>-->
                       $divHtml
                    </div>
                  <style>
                  .table-top-title{
                    height: 30px;
                    line-height: 30px;
                    font-size: 14px;
                    margin-top: 20px;
                    display: flex;
                    flex-direction: row;
                    justify-content: space-between;
                  }
</style>
eof;
        $print = new printClass();

        return $print->showPrint($html);
    }

    /**
     *JS
     */
    private function homeJs()
    {
        return <<<eof
<script>
$(".divider").parent().parent().css('background-color','#f2f2f2')
</script>
<style>
.divider{position: relative}
.divider>img{position: absolute;top: -62px;left: 90px}
</style>
eof;

    }

    /**
     * 导出
     */
    #[NoReturn] public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $tr = [];
            $sql = static::rGet(self::$stid.self::page . 'sql');
            $createTime = static::rGet(self::$stid.self::page . 'time');
            $timeWhere =$voucherWhere= '';
            $startDate = '';
            if ($createTime) {
                $data = explode('~', $createTime);
                $startDate = trim($data[0]);
                $timeWhere .= self::timeComparison($createTime, 'month', field: 'recordDate');
                $voucherWhere .= self::timeComparison($createTime, 'month', field: 'a.recordDate');
            }
            $title = array("项目", "名称", "期初", '借方(收入)', '贷方(支出)', '余额');
            $result = self::sqlFind($sql);
            if (is_array($result)) {
                foreach ($result as $array) {
                    $subject = query('subject', "id = '$array[subjectId]'");
                    $subjectInitMoney = find(array('table' => 'voucher as a join voucher_detail as b on a.id = b.orderId', 'single' => "b.subjectId = '$array[subjectId]' and b.direction = '借' and a.isTemplate = '否' and a.coid = '" . self::$coid . "' and date_format(a.recordDate,'%Y-%m') <'$startDate'", 'field' => "ifnull(sum(b.money),0) as money"))['money'];
                    $subjectInitMoney += $subject['initMoney'];
                    $subjectInitMoney = self::centToYuan($subjectInitMoney);//科目期初金额

                    $jieMoney = find(array('table' => 'voucher as a join voucher_detail as b on a.id = b.orderId', 'single' => "b.subjectId = '$array[subjectId]' and b.direction = '借' and a.isTemplate = '否' and a.coid = '" . self::$coid . "'" . $voucherWhere, 'field' => "ifnull(sum(b.money),0) as money"))['money'];
                    $daiMoney = find(array('table' => 'voucher as a join voucher_detail as b on a.id = b.orderId', 'single' => "b.subjectId = '$array[subjectId]' and b.direction = '贷' and a.isTemplate = '否' and a.coid = '" . self::$coid . "'" . $voucherWhere, 'field' => "ifnull(sum(b.money),0) as money"))['money'];
                    $jieMoney = self::centToYuan($jieMoney);
                    $daiMoney = self::centToYuan($daiMoney);

                    $initMoney = find(array('table' => 'bookkeeping', 'single' => "accountId = '$array[id]' and date_format(recordDate,'%Y-%m') < '$startDate'", 'field' => "ifnull(sum(income-expenses),0) as money"))['money'];
                    $initMoney += $array['initMoney'];
                    $income = find(array('table' => 'bookkeeping', 'where' => "accountId = '$array[id]'" . $timeWhere, 'sum' => "income"));
                    $out = find(array('table' => 'bookkeeping', 'where' => "accountId = '$array[id]'" . $timeWhere, 'sum' => "expenses"));

                    $hide = '';
                    if ($subjectInitMoney - $initMoney != 0) {
                        $hide = '不平';
                    }
                    if ($jieMoney - $income != 0) {
                        $hide = '不平';
                    }
                    if ($daiMoney - $out != 0) {
                        $hide = '不平';
                    }
                    $tr[] = ['会计科目', $subject['code'] . $subject['name'], $subjectInitMoney, $jieMoney, $daiMoney, $subjectInitMoney + $jieMoney - $daiMoney];
                    $tr[] = ['资金账户', $array['name'], $initMoney, $income, $out, $initMoney + $income - $out];
                    $tr[] = ["差异", $hide, round($subjectInitMoney - $initMoney,2), round($jieMoney - $income,2), round($daiMoney - $out,2), round(($subjectInitMoney + $jieMoney - $daiMoney) - ($initMoney + $income - $out),2)];
                }
            }
            $text = $this->control['name'] . "导出了核对总账";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $tr, "核对总账.xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }
}

